﻿using CRM.Infrastructure.Attr;
using CRM.Infrastructure.Dto.Request.Login;
using CRM.Infrastructure.Dto.Response;
using CRM.Infrastructure.Tools;
using CRM.Service.Interface;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

namespace CRM.Api.Admin.Controllers
{
    public class LoginController : BaseController
    {
        private readonly IConfiguration _configuration;

        public LoginController(IConfiguration configuration, I_Login_Service login_Service) : base(login_Service)
        {

            _configuration = configuration;


        }

        /// <summary>
        /// 管理员登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Logins(Login_Request_Dto dto)
        {
            dto.code = Config.GUID_2();
            var result = await _login_Service.Logins(dto);
            if (result.code == 0)
            {
                //登录成功 生成token
                Claim[] claims = new Claim[] {
                    new Claim(ClaimTypes.Name,dto.code),
                    new Claim(ClaimTypes.Role,"admin")
                };
                var token = JWTUtil.EnJwt(claims, _configuration["JWT:secretKey"]!,
                    _configuration["JWT:issuer"]!);
                result.data = token;
            }
            return Ok(result);
        }
        /// <summary>
        /// 检查用户登录信息是否有效
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public async Task<IActionResult> Check_Login()
        {
            // 可以在这里进行多线程处理 


            var user = await this.Get_Curr_User();//await 强制同步

            return Ok(new Api_Response_Dto
            {
                code = Api_Code.ok,
                message = "ok",
                data = new
                {
                    account = user.UAccount,
                    name = user.UName
                }
            });
        }


    }
}
